package com.example.demo.interceptor;

import com.example.demo.constant.Constant;
import com.example.demo.model.Result;
import com.example.demo.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j  //日志
public class LoginInterceptor implements HandlerInterceptor {        //定义拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle执行前");
        HttpSession session=request.getSession(false);
        //true 放行  false 拦截
       if(!checkUser(session)){
           response.setStatus(401);
           String msg="用户未登录";
           response.getOutputStream().write(msg.getBytes("UTF-8"));
           return false;
       }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle....");


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion.....");

    }

    public boolean checkUser(HttpSession session){
        if(session==null||session.getAttribute(Constant.SESSION_USER_KEY)==null){
            return false;
        }
        UserInfo userInfo=(UserInfo) session.getAttribute(Constant.SESSION_USER_KEY);
        if(userInfo==null||userInfo.getId()<=0){
            log.error("用户未登录");
            //用户未登录
            return false;
        }
        log.info("用户已登录");
        return true;
    }
}
